package com.art.sunflower.service.impl;

import com.art.sunflower.exception.NullWorkException;
import com.art.sunflower.mapper.WorkMapper;
import com.art.sunflower.pojo.User;
import com.art.sunflower.pojo.Work;
import com.art.sunflower.service.WorkService;
import com.art.sunflower.util.MyPageInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class WorkServiceImpl implements WorkService {
    @Resource
    WorkMapper workMapper;

    @Override
    public int insertWork(Work work) {
        return workMapper.insertWork(work);
    }

    @Override
    public int updateWork(Work work) {
        return workMapper.updateWork(work);
    }

    @Override
    public int deleteWork(int id) {

        return workMapper.deleteWork(id);
    }

    @Override
    public Work selectOneWork(int id) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        int teacherId = workMapper.selectTea(user.getId());
        return workMapper.selectOneWork(id, teacherId);
    }

    @Override
    public int updateRank(int id, boolean rank) {
        return workMapper.updateRank(id, rank);
    }

    @Override
    public int selectTea(int id) {
        return workMapper.selectTea(id);
    }

    @Override
    public List<Map<String, Object>> getAllWork() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        List<Map<String, Object>> selectStudentsClassesIds = workMapper.selectStudentsClassesIds(user.getId());
        for (Map<String, Object> selectStudentsClassesId : selectStudentsClassesIds) {
            List<Map<String, Object>> classesWork = workMapper.selectClassesWork((Integer) selectStudentsClassesId.get("classesId"));
            selectStudentsClassesId.put("classesWork", classesWork);
        }
        return selectStudentsClassesIds;
    }

    @Override
    public MyPageInfo listAllWork(Integer pageSize, Integer pageNo) throws NullWorkException {
        //需要进行分页
        PageHelper.startPage(pageNo, pageSize);
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        int teacherId = workMapper.selectTea(user.getId());
        List<Map<String, Object>> work = workMapper.listAllWork(teacherId);
        if (work.size() == 0)
            throw new NullWorkException();
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(work);
        return new MyPageInfo(pageInfo);
    }
}
